import { message } from "ant-design-vue";
import { defineComponent, ref, watchEffect } from "vue";

declare const docx: { renderAsync: (...args) => Promise<any> };


const Word = defineComponent({
  props: ["cache", "url", "fileName", "ext", "visibility"],
  emits: ["complete"],
  setup(props, ctx) {
    const wordRef = ref(null);

    const pushHtml = (dom: HTMLElement, buffer: ArrayBuffer) => {
      try {
        return docx.renderAsync(buffer, dom);
      } finally {
        ctx.emit("complete");
      }
    };


    const completeView = (dom: HTMLElement, buffer: ArrayBuffer) => {
      return pushHtml(dom, buffer)
        .then((rs) => {
          console.log(rs);
          const id = setTimeout(() => {
            clearTimeout(id);

            // props.cache.set(props.url + props.fileName + props.ext, buffer);
            ctx.emit("complete");
            // 设置缓存
          }, 800);
        })
        .catch(exx => {
          console.log(exx);
          message.error("预览错误");
        });
    };

    const loadWordHtml = () => {
      fetch(props.url)
        .then(rs => rs.arrayBuffer())
        .then(ab => {
          console.log(ab);
          completeView(wordRef.value, ab);
        });
    };

    watchEffect(() => {
      if (props.visibility) {
        if (props.cache.has(props.url + props.fileName + props.ext)) {
          pushHtml(wordRef.value, props.cache.get(props.url + props.fileName + props.ext));
          return;
        }
        loadWordHtml();
      }
    });

    return () => {
      return (
        <div ref={wordRef}>
        </div>
      );
    };
  },
});

export default Word;
